import {
  login,
  getCurrentUser
} from '@/api/after-sale/login'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth';
import store from '@/store'
import Cookie from 'js-cookie'

const user = {
  state: {
    token: getToken(),
    name: '',
    id: '',
    companyName: '',
    roles: [],
    buttons: [],
    user: {},
    entryStore: '', //入职门店
    stores: [], //登录人门店
    storesCalue: '', //门店选中值
    userInfo:{}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_COMPANYNAME: (state, comName) => {
      state.companyName = comName
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons
    },
    SET_STORES: (state, stores) => {
      state.stores = stores
    },
    SET_STORES_CALUE: (state, value) => {
      state.storesCalue = value
    },
    SET_STORES_USER_INFO: (state, value) => {
      state.userInfo = value
    },
    set_entryStore: (state, value) => {
      state.entryStore = value
    }
  },

  actions: {
    // 用户名登录
    login({
      commit
    }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(data => {
          //设置tokin
          let {
            success,
            data: tokin
          } = data;
          if (success) {
            setToken(tokin)
          }
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    getUserInfo({
      commit
    }) {
      return new Promise((resolve, reject) => {
        getCurrentUser().then(data => {
          let {
            success,
            data: {
              userName,
              menus,
              menuButtons,
              account,
              id,
              stores,
              storeId,
            }
          } = data;
          /**
           * ===========设置当前登录用户信息=============
           */
          if (success) {
            if (!account) {
              reject('Verification failed, please Login again.')
            }
            Cookie.set('user', account)
            sessionStorage.setItem('login',JSON.stringify(data.data))
            commit('SET_USER', account)
            commit('SET_NAME', userName)
            commit('SET_ROLES', menus)
            commit('SET_STORES_USER_INFO',data.data)
            if (stores.length > 1) {
              stores.push({
                children: null,
                id: '',
                storeLevel: '',
                storeName: "全部",
              })
            }
            if(stores.length==1){
              commit("SET_STORES_CALUE", stores[0].id)
            }
            commit("SET_STORES", stores)
            commit("set_entryStore", storeId) //设置入职门店
            commit("SET_ID", id);
            //重置按钮权限
            this.state.buttons = []
            //存所有按钮权限
            const btn = findAllBtn(menus);
            // console.log(menuButtons)
            commit('SET_BUTTONS', menuButtons);
            resolve({
              roles: menus,
              account: account
            })
          }
          console.log('获取当前登录用户信息及权限', data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({
      dispatch,
      state
    }) {
      return new Promise((resolve, reject) => {
        dispatch('FedLogOut')
        removeToken()
        resolve(state)
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ID', '')
        commit('SET_NAME', '')
        commit('SET_ROLES', [])
        commit('SET_BUTTONS', [])
        Cookie.remove('id')
        removeToken()
        resolve()
      })
    }

    // // 动态修改权限
    // ChangeRoles({ commit }, role) {
    //   return new Promise(resolve => {
    //     commit('X-Auth-Token', role)
    //     // setToken(role)
    //     // getUserInfo(role).then(response => {
    //     //   const data = response.data
    //     //   commit('SET_ROLES', data.roles)
    //     //   commit('SET_NAME', data.name)
    //     //   commit('SET_AVATAR', data.avatar)
    //     //   commit('SET_INTRODUCTION', data.introduction)
    //     //   resolve()
    //     // })
    //   })
    // }
  }
}

export function findAllBtn(list) {
  list.forEach(val => {
    // 与后台协商所有菜单资源（resCode)下的type是MENU表菜单，BUTTON为按钮
    if (val.type === 'MENU') {
      if (val.children && val.children.length > 0) {
        findAllBtn(val.children)
      }
    } else {
      user.state.buttons.push(val.id)
    }
  })
  return user.state.buttons;
}


export default user
